import pandas as pd

from forms.uipy.UI_RationalUpCal import Ui_RationalUpCal
from PySide2.QtWidgets import QWidget, QButtonGroup, QRadioButton
from PySide2.QtGui import QStandardItemModel, QStandardItem, QKeySequence, QClipboard
from PySide2.QtCore import Qt
from tools.File_Select_Tools import File_Select_Tools
from server.RationalUpCalServer import RationalUpCalServer
from tools.Area_Objects import areaObjs
from functools import cmp_to_key


class RationalUpCalImpl(QWidget, Ui_RationalUpCal):
    """
    合理性和增长性数据（采集）实现类
    """

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.btg = QButtonGroup(self)
        cit_radio = QRadioButton("城镇")
        cit_radio.setChecked(True)
        cot_radio = QRadioButton("农村")
        self.btg.addButton(cit_radio)
        self.btg.addButton(cot_radio)
        self.rd_group.addWidget(cit_radio)
        self.rd_group.addWidget(cot_radio)

        self.btg.buttonClicked.connect(self.cit_or_cot_handle)
        self.set_data_formate()
        self.show_table.setModel(self.model)

        # 绑定文件选择
        self.pre_path_btn.clicked.connect(
            lambda: self.pre_data_path.setText(File_Select_Tools.select_one_file(title="上季度分户数据")[0]))
        self.now_path_btn.clicked.connect(
            lambda: self.now_data_path.setText(File_Select_Tools.select_one_file(title="当前季分户数据")[0]))
        self.village_path_btn.clicked.connect(
            lambda: self.village_data_path.setText(File_Select_Tools.select_one_file(title="小区样本数据")[0]))
        self.ok_btn.clicked.connect(self.ok_btn_handle)

    def ok_btn_handle(self):
        pre_data_path = self.pre_data_path.text()
        now_data_path = self.now_data_path.text()
        village_data_path = self.village_data_path.text()
        btg_select = self.btg.checkedButton().text()
        if len(pre_data_path) <= 0 or len(now_data_path) <= 0:
            return False
        # data = []
        ru = RationalUpCalServer(pre_data_path, now_data_path,village_data_path)
        if self.jd_select.currentText() == "当前季度":
            if btg_select == "城镇":
                temp = ru.now_data_df[ru.now_data_df["城乡类别"].isin([1])].copy()

                temp_con = ru.now_con_df[ru.now_con_df["城乡类别"].isin([1])].copy()
                data = self.get_all_data(ru, temp, temp_con, 1)
                self.set_data_formate(1)
            elif btg_select == "农村":
                temp = ru.now_data_df[ru.now_data_df["城乡类别"].isin([2])].copy()
                temp_con = ru.now_con_df[ru.now_con_df["城乡类别"].isin([2])].copy()
                data = self.get_all_data(ru, temp, temp_con, 1)
                self.set_data_formate(1)
        elif self.jd_select.currentText() == "上季度":
            if btg_select == "城镇":
                temp = ru.pre_data_df[ru.pre_data_df["城乡类别"].isin([1])].copy()
                temp_con = ru.pre_data_df[ru.pre_data_df["城乡类别"].isin([1])].copy()
                data = self.get_all_data(ru, temp, temp_con)
                self.set_data_formate()
            elif btg_select == "农村":
                temp = ru.pre_data_df[ru.pre_data_df["城乡类别"].isin([2])].copy()
                temp_con = ru.pre_data_df[ru.pre_data_df["城乡类别"].isin([2])].copy()
                data = self.get_all_data(ru, temp, temp_con)
                self.set_data_formate()

        # print(data)
        self.add_table_data(data)
        self.show_table.setModel(self.model)

    def get_all_data(self, ru, df, con_df, current_quarter=0):
        res = []
        """
        获取全市数据
        :return: 
        """
        # with pd.ExcelWriter("./泸州市城镇户.xlsx") as writer4:
        #     with pd.ExcelWriter("./泸州城镇共同户.xlsx") as writer1:
        #         with pd.ExcelWriter("./泸州城镇剔除共同户.xlsx") as writer2:
        #             with pd.ExcelWriter("./泸州城镇剔除后剩余共同户.xlsx") as writer3:
        #                 for object in areaObjs:
        #                     if not object["No"] == 510500:
        #                         temp = df[df["coun"] == object["No"]]
        #                         temp_con = con_df[con_df["coun"] == object["No"]]
        #                         res.append(ru.layout_data(temp, temp_con, current_quarter))
        #
        #                         temp.to_excel(writer4, sheet_name=object["name"], index=False)
        #                         ru.connnn.to_excel(writer1, sheet_name=object["name"], index=False)
        #                         ru.out_hu.to_excel(writer2, sheet_name=object["name"], index=False)
        #                         ru.resHouseDf_out.to_excel(writer3, sheet_name=object["name"], index=False)
        #                     else:
        #                         res.append(ru.layout_data(df, con_df, current_quarter))
        #
        #                         df.to_excel(writer4, sheet_name=object["name"], index=False)
        #                         ru.connnn.to_excel(writer1,sheet_name=object["name"],index=False)
        #                         ru.out_hu.to_excel(writer2, sheet_name=object["name"],index=False)
        #                         ru.resHouseDf_out.to_excel(writer3,sheet_name=object["name"],index=False)

        for object in areaObjs:
            if not object["No"] == 510500:
                temp = df[df["coun"] == object["No"]]
                temp_con = con_df[con_df["coun"] == object["No"]]
                res.append(ru.layout_data(temp, temp_con, current_quarter))
            else:
                res.append(ru.layout_data(df, con_df, current_quarter))
                # ru.connnn.to_excel("./泸州城镇共同户.xlsx", index=False)
                # ru.out_hu.to_excel("./泸州城镇剔除共同户.xlsx", index=False)
                # ru.resHouseDf_out.to_excel("./泸州城镇剔除后剩余共同户.xlsx",index=False)

        return res

    def set_data_formate(self, flag=0):
        self.model = QStandardItemModel()
        self.model.setItem(0, 0, QStandardItem("单位"))
        self.model.setItem(0, 1, QStandardItem("不加权人均"))
        self.model.setItem(1, 1, QStandardItem("人均收入"))
        self.model.setItem(1, 2, QStandardItem("人均消费支出"))
        self.model.setItem(0, 3, QStandardItem("加权剔除最高和最低2%"))
        self.model.setItem(1, 3, QStandardItem("人均收入"))
        self.model.setItem(1, 4, QStandardItem("人均消费支出"))
        self.model.setItem(0, 5, QStandardItem("加权中位户绝对值%"))
        self.model.setItem(1, 5, QStandardItem("人均收入"))
        self.model.setItem(1, 6, QStandardItem("人均消费支出"))
        self.model.setItem(0, 7, QStandardItem("加权连续户绝对值%"))
        self.model.setItem(1, 7, QStandardItem("人均收入"))
        self.model.setItem(1, 8, QStandardItem("人均消费支出"))
        self.model.setItem(2, 0, QStandardItem("全市"))
        self.model.setItem(3, 0, QStandardItem("江阳区"))
        self.model.setItem(4, 0, QStandardItem("纳溪区"))
        self.model.setItem(5, 0, QStandardItem("龙马潭区"))
        self.model.setItem(6, 0, QStandardItem("泸县"))
        self.model.setItem(7, 0, QStandardItem("合江县"))
        self.model.setItem(8, 0, QStandardItem("叙永县"))
        self.model.setItem(9, 0, QStandardItem("古蔺县"))
        self.show_table.setSpan(0, 0, 2, 1)
        self.show_table.setSpan(0, 1, 1, 2)
        self.show_table.setSpan(0, 3, 1, 2)
        self.show_table.setSpan(0, 5, 1, 2)
        self.show_table.setSpan(0, 7, 1, 2)
        if flag == 1:
            # 创建当前季独有数据
            self.model.setItem(0, 9, QStandardItem("连续户数"))
            self.model.setItem(0, 10, QStandardItem("连续户收入增长户数"))
            self.model.setItem(0, 11, QStandardItem("连续户消费增长户数"))
            self.show_table.setSpan(0, 9, 2, 1)
            self.show_table.setSpan(0, 10, 2, 1)
            self.show_table.setSpan(0, 11, 2, 1)
            pass

        # 设置每个都居中对齐
        # for row in range(self.pre_model.rowCount()):
        #     for col in range(self.pre_model.columnCount()):
        #         item = self.pre_model.item(row, col)
        #         item.setEditable(False)
        # item.setTextAlignment(Qt.AlignCenter)
        # self.show_table.setItemDelegate()

    def add_table_data(self, data):
        """
        :param data: 二维表
        :return:
        """
        for row in range(len(data)):
            for col in range(len(data[row])):
                self.model.setItem(2 + row, 1 + col, QStandardItem(str(data[row][col])))

    def keyPressEvent(self, event):
        # 重写键盘按下事件
        if event.matches(QKeySequence.StandardKey.Copy):
            select_items = self.show_table.selectedIndexes()
            if len(select_items) > 0:
                # 使用cmp_to_key转换, 排序
                select_items = sorted(select_items, key=cmp_to_key(self.__sort_select_items))
                # 行数
                row_num = select_items[0].row()

                min_row = select_items[0].row()
                max_row = select_items[-1].row()
                min_col = select_items[0].column()
                temp_min_col = min_col
                max_col = select_items[-1].column()
                # for item in select_items:
                #     if item.row() == row_num:
                #         str = str + item.data() + "\t"
                #     else:
                #         str = str + "\n" + item.data()+"\t"
                #         row_num = item.row()
                str_arr = []
                while min_row <= max_row:
                    row = []
                    while temp_min_col <= max_col:
                        flag = 0
                        for item in select_items:
                            if item.row() == min_row and item.column() == temp_min_col:
                                row.append(item.data())
                                flag = 1
                                break
                        if flag == 0:
                            row.append("")
                        temp_min_col += 1
                        flag = 0
                    temp_min_col = min_col
                    str_arr.append(row)
                    min_row += 1
                # 添加到剪切板
                # 将二维数组转化为字符串
                # 添加到剪贴板数据
                str = ""
                for row in str_arr:
                    for col in row:
                        str += col + "\t"
                    str += "\n"
                # print(str)
                # 获取剪切板对象
                QClipboard().setText(str)
                # print(min_row,max_row)
                # print(min_col,max_col)

    def __sort_select_items(self, a, b):
        """
        自定义排序选择数据 1 0 -1
        :param a: 当前项
        :param b: 后一项
        :return:
        """
        if a.row() < b.row():
            return -1
        elif a.row() == b.row():
            # 同行，排序列
            if a.column() < b.column():
                return -1
            elif a.column() == b.column():
                return 0
            else:
                return 1
        else:
            return 1

    def cit_or_cot_handle(self):
        # print(self.btg.checkedButton().text())
        pass
